/**
 * 元素管理模块
 * 负责元素的创建、渲染、样式管理等核心功能
 */
class ElementManager {
    constructor(canvas, propertiesPanel) {
        this.canvas = canvas;
        this.propertiesPanel = propertiesPanel;
        this.elements = [];
        this.elementIdCounter = 0;
        this.selectedElement = null;
        this.currentPageIndex = 0;
    }

    /**
     * 设置当前页面索引
     * @param {number} pageIndex - 页面索引
     */
    setCurrentPage(pageIndex) {
        this.currentPageIndex = pageIndex;
    }

    /**
     * 获取当前页面索引
     * @returns {number} 当前页面索引
     */
    getCurrentPageIndex() {
        return this.currentPageIndex;
    }

    /**
     * 加载页面元素
     * @param {Array} elements - 元素数组
     */
    loadPageElements(elements) {
        console.log('loadPageElements called:', {
            canvas: this.canvas,
            canvasDataPage: this.canvas ? this.canvas.getAttribute('data-page') : 'no canvas',
            elementsCount: elements ? elements.length : 0,
            currentPageIndex: this.currentPageIndex
        });
        
        // 清空画布上的所有元素
        this.canvas.innerHTML = '';
        
        // 更新元素数组
        this.elements = elements || [];
        
        // 更新元素ID计数器
        if (this.elements.length > 0) {
            this.elementIdCounter = Math.max(...this.elements.map(el => parseInt(el.id.split('_')[1]) || 0), 0);
        } else {
            this.elementIdCounter = 0;
        }
        
        console.log('About to render elements:', this.elements.length);
        
        // 渲染元素
        this.renderElements();
        
        console.log('Elements rendered to canvas');
        
        // 更新画布提示文案
        this.updateCanvasPlaceholder();
    }

    /**
     * 获取当前页面元素
     * @returns {Array} 当前页面元素数组
     */
    getCurrentPageElements() {
        return this.elements;
    }

    /**
     * 渲染所有元素
     */
    renderElements() {
        this.elements.forEach(element => {
            this.renderElement(element);
        });
    }

    /**
     * 获取元素的默认样式
     * @param {string} type - 元素类型
     * @returns {Object} 默认样式对象
     */
    getDefaultStyle(type) {
        const defaultStyles = {
            text: {
                width: '120px',
                height: '40px',
                fontSize: '16px',
                color: '#333333',
                backgroundColor: 'transparent',
                textAlign: 'center',
                borderWidth: '0px',
                borderColor: '#000000',
                borderStyle: 'none',
                borderRadius: '0px',
                padding: '8px',
                position: 'absolute',
                animationName: 'none',
                animationDuration: '1s',
                animationDelay: '0s',
                animationIterationCount: '1',
                animationFillMode: 'both'
            },
            image: {
                width: '100px',
                height: '100px',
                // borderWidth: '1px',
                // borderColor: '#dddddd',
                // borderStyle: 'solid',
                // borderRadius: '4px',
                position: 'absolute',
                objectFit: 'cover',
                animationName: 'none',
                animationDuration: '1s',
                animationDelay: '0s',
                animationIterationCount: '1',
                animationFillMode: 'both'
            },
            button: {
                width: '100px',
                height: '40px',
                fontSize: '14px',
                color: '#ffffff',
                backgroundColor: '#007bff',
                textAlign: 'center',
                borderWidth: '0px',
                borderColor: '#000000',
                borderStyle: 'none',
                borderRadius: '4px',
                cursor: 'pointer',
                position: 'absolute',
                animationName: 'none',
                animationDuration: '1s',
                animationDelay: '0s',
                animationIterationCount: '1',
                animationFillMode: 'both'
            },
            input: {
                width: '150px',
                height: '40px',
                fontSize: '14px',
                color: '#333333',
                backgroundColor: '#ffffff',
                textAlign: 'left',
                borderWidth: '1px',
                borderColor: '#dddddd',
                borderStyle: 'solid',
                borderRadius: '4px',
                padding: '8px',
                position: 'absolute',
                animationName: 'none',
                animationDuration: '1s',
                animationDelay: '0s',
                animationIterationCount: '1',
                animationFillMode: 'both'
            },
            grid: {
                width: '300px',
                height: '150px',
                display: 'grid',
                gap: '10px',
                padding: '15px',
                borderWidth: '2px',
                borderColor: '#007bff',
                borderStyle: 'dashed',
                backgroundColor: '#f8f9fa',
                borderRadius: '8px',
                position: 'relative',
                animationName: 'none',
                animationDuration: '1s',
                animationDelay: '0s',
                animationIterationCount: '1',
                animationFillMode: 'both'
            }
        };
        return defaultStyles[type] || {};
    }

    /**
     * 获取元素的默认内容
     * @param {string} type - 元素类型
     * @returns {string} 默认内容
     */
    getDefaultContent(type) {
        const defaultContents = {
            text: '文本内容',
            image: '/images/demo.webp',
            button: '按钮',
            input: '',
            grid: ''
        };
        return defaultContents[type] || '';
    }

    /**
     * 创建新元素
     * @param {string} type - 元素类型
     * @param {number} x - X坐标
     * @param {number} y - Y坐标
     * @param {number} cols - 网格列数（仅网格元素）
     * @returns {Object} 元素对象
     */
    createElement(type, x, y, cols = null) {
        const elementId = `element_${++this.elementIdCounter}`;
        
        // 获取当前画布上所有元素的最大z-index
        const maxZIndex = this.getMaxZIndex();
        
        const element = {
            id: elementId,
            type: type,
            x: x,
            y: y,
            style: { ...this.getDefaultStyle(type) },
            content: this.getDefaultContent(type),
            parentGrid: null
        };

        // 设置新元素的z-index，从10开始递增
        element.style.zIndex = Math.max(maxZIndex + 1, 10);

        // 如果是网格元素，设置列数
        if (type === 'grid' && cols) {
            element.cols = cols;
            element.style.gridTemplateColumns = `repeat(${cols}, 1fr)`;
        }

        this.elements.push(element);
        
        // 更新画布提示文案显示状态
        this.updateCanvasPlaceholder();
        
        return element;
    }

    /**
     * 获取当前画布上所有元素的最大z-index
     * @returns {number} 最大z-index值
     */
    getMaxZIndex() {
        let maxZIndex = 0;
        
        // 检查画布上所有元素的z-index
        const canvasElements = this.canvas.querySelectorAll('.canvas-element');
        canvasElements.forEach(el => {
            const zIndex = parseInt(el.style.zIndex) || 0;
            if (zIndex > maxZIndex) {
                maxZIndex = zIndex;
            }
        });
        
        // 检查elements数组中的z-index
        this.elements.forEach(element => {
            const zIndex = parseInt(element.style.zIndex) || 0;
            if (zIndex > maxZIndex) {
                maxZIndex = zIndex;
            }
        });
        
        return maxZIndex;
    }

    /**
     * 渲染元素到画布
     * @param {Object} element - 元素对象
     */
    renderElement(element) {
        // 移除已存在的元素（避免重复渲染）
        const existingElement = document.getElementById(element.id);
        if (existingElement) {
            existingElement.remove();
        }

        const elementDiv = document.createElement('div');
        elementDiv.id = element.id;
        elementDiv.className = 'canvas-element';
        
        // 强制设置position为absolute
        elementDiv.style.setProperty('position', 'absolute', 'important');
        elementDiv.style.left = element.x + 'px';
        elementDiv.style.top = element.y + 'px';
        elementDiv.style.cursor = 'move';
        elementDiv.style.userSelect = 'none';
        elementDiv.style.zIndex = element.style.zIndex || 1;

        // 根据元素类型创建内容
        switch (element.type) {
            case 'text':
                elementDiv.textContent = element.content;
                // 确保文字元素有足够的空间显示动画
                if (!element.style.width || element.style.width === '0px') {
                    elementDiv.style.minWidth = '120px';
                }
                if (!element.style.height || element.style.height === '0px') {
                    elementDiv.style.minHeight = '40px';
                }
                break;
            case 'image':
                const img = document.createElement('img');
                img.src = element.content;
                img.style.cssText = 'width: 100%; height: 100%; object-fit: cover; display: block;';
                img.onerror = () => {
                    img.style.display = 'none';
                    elementDiv.textContent = '图片加载失败';
                    elementDiv.style.display = 'flex';
                    elementDiv.style.alignItems = 'center';
                    elementDiv.style.justifyContent = 'center';
                    elementDiv.style.backgroundColor = '#f8f9fa';
                    elementDiv.style.border = '1px dashed #ccc';
                };
                img.onload = () => {
                    img.style.display = 'block';
                };
                elementDiv.appendChild(img);
                // 确保div和img都有相同的border-radius以支持圆角效果
                const borderRadius = element.style.borderRadius || '0px';
                elementDiv.style.borderRadius = borderRadius;
                img.style.borderRadius = borderRadius;
                break;
            case 'button':
                elementDiv.textContent = element.content;
                break;
            case 'input':
                const input = document.createElement('input');
                input.type = 'text';
                input.value = element.content;
                input.placeholder = '请输入内容';
                input.style.cssText = 'width: 100%; height: 100%; border: none; outline: none; background: transparent;';
                elementDiv.appendChild(input);
                break;
            case 'grid':
                elementDiv.innerHTML = `
                    <div class="grid-header" style="
                        font-size: 12px;
                        color: #666;
                        margin-bottom: 10px;
                        text-align: center;
                        font-weight: bold;
                    ">${element.cols || 2}列网格</div>
                    <div class="grid-content" style="
                        display: grid;
                        gap: 10px;
                        height: calc(100% - 30px);
                    " data-grid-id="${element.id}">
                        <div class="grid-hint" style="
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            color: #999;
                            font-size: 12px;
                            border: 1px dashed #ccc;
                            border-radius: 4px;
                        ">拖拽元素到此处</div>
                    </div>
                `;
                this.setupGridDropZone(elementDiv, element);
                break;
        }

        // 应用样式
        Object.entries(element.style).forEach(([key, value]) => {
            const cssKey = key.replace(/([A-Z])/g, '-$1').toLowerCase();
            if (cssKey === 'position') {
                // 强制设置position为absolute，忽略元素数据中的position值
                elementDiv.style.setProperty(cssKey, 'absolute', 'important');
            } else {
                elementDiv.style[cssKey] = value;
            }
        });
        
        // 确保position始终为absolute
        elementDiv.style.setProperty('position', 'absolute', 'important');

        // 应用事件处理
        this.applyEventHandlers(elementDiv, element);

        // 应用动画类
        if (element.style.animationName && element.style.animationName !== 'none') {
            elementDiv.classList.add('animate__animated', `animate__${element.style.animationName}`);
            elementDiv.style.setProperty('--animate-duration', element.style.animationDuration);
            elementDiv.style.setProperty('--animate-delay', element.style.animationDelay);
            elementDiv.style.animationFillMode = element.style.animationFillMode;
            
            // 处理动画次数
            if (element.style.animationIterationCount === 'infinite') {
                elementDiv.classList.add('animate__infinite');
            } else {
                elementDiv.classList.add(`animate__repeat-${element.style.animationIterationCount}`);
            }
        }

        this.canvas.appendChild(elementDiv);

        // 设置拖拽功能
        this.makeDraggable(elementDiv, element);

        // 设置调整大小功能
        this.addResizeHandles(elementDiv, element);

        return elementDiv;
    }

    /**
     * 设置元素拖拽功能
     * @param {HTMLElement} elementDiv - DOM元素
     * @param {Object} element - 元素对象
     */
    makeDraggable(elementDiv, element) {
        let isDragging = false;
        let startX, startY, startLeft, startTop, offsetX, offsetY;

        const handleDragStart = (e) => {
            if (e.target.classList.contains('resize-handle')) return;
            
            // 选择元素（selectElement方法已经会设置z-index）
            this.selectElement(element);
            
            isDragging = true;
            const rect = elementDiv.getBoundingClientRect();
            const canvasRect = this.canvas.getBoundingClientRect();
            
            const clientX = e.clientX || (e.touches && e.touches[0].clientX);
            const clientY = e.clientY || (e.touches && e.touches[0].clientY);
            
            offsetX = clientX - rect.left;
            offsetY = clientY - rect.top;
            startX = clientX;
            startY = clientY;
            startLeft = element.x;
            startTop = element.y;

            // 阻止事件冒泡到Swiper
            e.stopPropagation();
            e.preventDefault();
            
            // 禁用Swiper滑动
            this.disableSwiper();
        };
        
        elementDiv.addEventListener('mousedown', handleDragStart);
        elementDiv.addEventListener('touchstart', handleDragStart, { passive: false });

        const handleDragMove = (e) => {
            if (!isDragging) return;

            const canvasRect = this.canvas.getBoundingClientRect();
            const clientX = e.clientX || (e.touches && e.touches[0].clientX);
            const clientY = e.clientY || (e.touches && e.touches[0].clientY);
            
            const newX = clientX - canvasRect.left - offsetX - 2;
            const newY = clientY - canvasRect.top - offsetY - 2;

            // 边界检查
            const maxX = this.canvas.offsetWidth - elementDiv.offsetWidth;
            const maxY = this.canvas.offsetHeight - elementDiv.offsetHeight;

            element.x = Math.max(0, Math.min(newX, maxX));
            element.y = Math.max(0, Math.min(newY, maxY));

            elementDiv.style.left = element.x + 'px';
            elementDiv.style.top = element.y + 'px';
            // 确保position始终保持为absolute
            elementDiv.style.setProperty('position', 'absolute', 'important');
        };
        
        const handleDragEnd = () => {
            if (isDragging) {
                isDragging = false;
                // 拖拽结束后更新属性面板
                this.updatePropertiesPanelValues(element);
                
                // 重新启用Swiper滑动
                this.enableSwiper();
            }
        };

        document.addEventListener('mousemove', handleDragMove);
        document.addEventListener('touchmove', handleDragMove, { passive: false });
        document.addEventListener('mouseup', handleDragEnd);
        document.addEventListener('touchend', handleDragEnd);
    }

    /**
     * 添加调整大小手柄
     * @param {HTMLElement} elementDiv - DOM元素
     * @param {Object} element - 元素对象
     */
    addResizeHandles(elementDiv, element) {
        if (element.type === 'grid') return; // 网格元素不支持调整大小

        const handle = document.createElement('div');
        handle.className = 'resize-handle';
        handle.style.cssText = `
            position: absolute;
            bottom: 0;
            right: 0;
            width: 10px;
            height: 10px;
            background: #007bff;
            cursor: se-resize;
            border-radius: 2px;
        `;
        elementDiv.appendChild(handle);

        let isResizing = false;
        let startX, startY, startWidth, startHeight;

        handle.addEventListener('mousedown', (e) => {
            isResizing = true;
            startX = e.clientX;
            startY = e.clientY;
            startWidth = parseInt(element.style.width);
            startHeight = parseInt(element.style.height);
            
            e.stopPropagation();
            e.preventDefault();
            
            // 禁用Swiper滑动
            this.disableSwiper();
        });

        document.addEventListener('mousemove', (e) => {
            if (!isResizing) return;

            const newWidth = startWidth + (e.clientX - startX);
            const newHeight = startHeight + (e.clientY - startY);

            // 边界检查
            const maxWidth = this.canvas.offsetWidth - element.x;
            const maxHeight = this.canvas.offsetHeight - element.y;

            element.style.width = Math.max(50, Math.min(newWidth, maxWidth)) + 'px';
            element.style.height = Math.max(30, Math.min(newHeight, maxHeight)) + 'px';

            elementDiv.style.width = element.style.width;
            elementDiv.style.height = element.style.height;
            // 确保position始终保持为absolute
            elementDiv.style.setProperty('position', 'absolute', 'important');
        });

        document.addEventListener('mouseup', () => {
            if (isResizing) {
                isResizing = false;
                // 调整大小结束后更新属性面板
                this.updatePropertiesPanelValues(element);
                
                // 重新启用Swiper滑动
                this.enableSwiper();
            }
        });
    }

    /**
     * 更新属性面板中的输入框值
     * @param {Object} element - 元素对象
     */
    updatePropertiesPanelValues(element) {
        if (!element || !this.selectedElement || this.selectedElement.id !== element.id) {
            return;
        }

        // 更新尺寸输入框
        const widthInput = document.getElementById('elementWidth');
        const heightInput = document.getElementById('elementHeight');
        if (widthInput) widthInput.value = parseInt(element.style.width);
        if (heightInput) heightInput.value = parseInt(element.style.height);

        // 更新z-index输入框
        const zIndexInput = document.getElementById('elementZIndex');
        if (zIndexInput) zIndexInput.value = parseInt(element.style.zIndex) || 0;
    }

    /**
     * 选择元素
     * @param {Object} element - 要选择的元素
     */
    selectElement(element) {
        // 移除之前选中的元素
        document.querySelectorAll('.canvas-element.selected').forEach(el => {
            el.classList.remove('selected');
        });

        this.selectedElement = element;

        if (element) {
            const elementDiv = document.getElementById(element.id);
            if (elementDiv) {
                elementDiv.classList.add('selected');
                this.showElementProperties(element);
            } else {
                console.warn('Element not found in DOM:', element.id);
            }
        } else {
            this.hideElementProperties();
        }
    }

    /**
     * 显示元素属性面板
     * @param {Object} element - 元素对象
     */
    showElementProperties(element) {
        if (!this.propertiesPanel) {
            console.warn('Properties panel not found');
            return;
        }
        
        const propertiesHTML = this.generatePropertiesHTML(element);
        const eventsHTML = this.generateEventsHTML(element);
        this.propertiesPanel.innerHTML = `
            <div class="properties-tabs">
                <button class="tab-btn active" data-tab="properties">属性</button>
                <button class="tab-btn" data-tab="events">事件</button>
            </div>
            <div class="properties-content">
                <div class="tab-content active" id="properties-tab">
                    ${propertiesHTML}
                </div>
                <div class="tab-content" id="events-tab">
                    ${eventsHTML}
                </div>
            </div>
            <button id="deleteElement" class="btn btn-danger">删除元素</button>
        `;
        this.propertiesPanel.style.display = 'block';
        this.setupPropertyListeners(element);
    }

    /**
     * 生成事件HTML
     */
    generateEventsHTML(element) {
        return `
            <div class="form-group">
                <label>点击事件</label>
                <select id="elementClickEvent" class="form-control">
                    <option value="none" ${element.events?.click === 'none' ? 'selected' : ''}>无</option>
                    <option value="alert" ${element.events?.click === 'alert' ? 'selected' : ''}>弹窗提示</option>
                    <option value="link" ${element.events?.click === 'link' ? 'selected' : ''}>跳转链接</option>
                    <option value="custom" ${element.events?.click === 'custom' ? 'selected' : ''}>自定义代码</option>
                </select>
            </div>
            
            <div class="form-group" id="clickLinkGroup" style="display: ${element.events?.click === 'link' ? 'block' : 'none'};">
                <label>链接地址</label>
                <input type="text" id="elementClickLink" class="form-control" value="${element.events?.clickLink || ''}" placeholder="https://example.com">
            </div>
            
            <div class="form-group" id="clickCustomGroup" style="display: ${element.events?.click === 'custom' ? 'block' : 'none'};">
                <label>自定义代码</label>
                <textarea id="elementClickCustom" class="form-control" rows="3" placeholder="console.log('clicked');">${element.events?.clickCustom || ''}</textarea>
            </div>
            
            <div class="form-group">
                <label>触摸事件</label>
                <select id="elementTouchEvent" class="form-control">
                    <option value="none" ${element.events?.touch === 'none' ? 'selected' : ''}>无</option>
                    <option value="alert" ${element.events?.touch === 'alert' ? 'selected' : ''}>弹窗提示</option>
                    <option value="link" ${element.events?.touch === 'link' ? 'selected' : ''}>跳转链接</option>
                    <option value="custom" ${element.events?.touch === 'custom' ? 'selected' : ''}>自定义代码</option>
                </select>
            </div>
            
            <div class="form-group" id="touchLinkGroup" style="display: ${element.events?.touch === 'link' ? 'block' : 'none'};">
                <label>链接地址</label>
                <input type="text" id="elementTouchLink" class="form-control" value="${element.events?.touchLink || ''}" placeholder="https://example.com">
            </div>
            
            <div class="form-group" id="touchCustomGroup" style="display: ${element.events?.touch === 'custom' ? 'block' : 'none'};">
                <label>自定义代码</label>
                <textarea id="elementTouchCustom" class="form-control" rows="3" placeholder="console.log('touched');">${element.events?.touchCustom || ''}</textarea>
            </div>
            
            <div class="form-group">
                <label>悬停事件</label>
                <select id="elementHoverEvent" class="form-control">
                    <option value="none" ${element.events?.hover === 'none' ? 'selected' : ''}>无</option>
                    <option value="alert" ${element.events?.hover === 'alert' ? 'selected' : ''}>弹窗提示</option>
                    <option value="custom" ${element.events?.hover === 'custom' ? 'selected' : ''}>自定义代码</option>
                </select>
            </div>
            
            <div class="form-group" id="hoverCustomGroup" style="display: ${element.events?.hover === 'custom' ? 'block' : 'none'};">
                <label>自定义代码</label>
                <textarea id="elementHoverCustom" class="form-control" rows="3" placeholder="console.log('hovered');">${element.events?.hoverCustom || ''}</textarea>
            </div>
        `;
    }

    /**
     * 隐藏元素属性面板
     */
    hideElementProperties() {
        if (this.propertiesPanel) {
            this.propertiesPanel.style.display = 'none';
        }
    }

    /**
     * 生成属性面板HTML
     * @param {Object} element - 元素对象
     * @returns {string} HTML字符串
     */
    generatePropertiesHTML(element) {
        let html = `
            <div class="form-group full-width">
                <label>内容:</label>
                <input type="text" id="elementContent" value="${element.content}" placeholder="请输入内容">
            </div>
        `;

        // 根据元素类型显示不同的属性
        if (element.type === 'text') {
            html += `
                <div class="form-group">
                    <label>字体大小 (px):</label>
                    <input type="number" id="fontSize" value="${parseInt(element.style.fontSize)}" step="1">
                </div>
                <div class="form-group">
                    <label>字体颜色:</label>
                    <div class="color-input-group">
                        <input type="color" id="textColor" value="${element.style.color}">
                        <span class="color-value" id="textColorValue">${element.style.color}</span>
                    </div>
                </div>
                <div class="form-group">
                    <label>文本对齐:</label>
                    <select id="textAlign">
                        <option value="left" ${element.style.textAlign === 'left' ? 'selected' : ''}>居左</option>
                        <option value="center" ${element.style.textAlign === 'center' ? 'selected' : ''}>居中</option>
                        <option value="right" ${element.style.textAlign === 'right' ? 'selected' : ''}>居右</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>背景颜色:</label>
                    <div class="color-input-group">
                        <input type="color" id="backgroundColor" value="${element.style.backgroundColor || '#ffffff'}">
                        <span class="color-value" id="backgroundColorValue">${element.style.backgroundColor || '#ffffff'}</span>
                    </div>
                </div>
            `;
        } else if (element.type === 'image') {
            html += `
                <div class="form-group full-width">
                    <label>图片URL:</label>
                    <input type="url" id="imageUrl" value="${element.content}">
                </div>
            `;
        } else if (element.type === 'button') {
            html += `
                <div class="form-group full-width">
                    <label>按钮文字:</label>
                    <input type="text" id="buttonText" value="${element.content}">
                </div>
                <div class="form-group">
                    <label>背景颜色:</label>
                    <div class="color-input-group">
                        <input type="color" id="buttonBgColor" value="${element.style.backgroundColor}">
                        <span class="color-value" id="buttonBgColorValue">${element.style.backgroundColor}</span>
                    </div>
                </div>
                <div class="form-group">
                    <label>文字颜色:</label>
                    <div class="color-input-group">
                        <input type="color" id="buttonTextColor" value="${element.style.color}">
                        <span class="color-value" id="buttonTextColorValue">${element.style.color}</span>
                    </div>
                </div>
            `;
        }

        html += `
            <div class="form-group">
                <label>宽度 (px):</label>
                <input type="number" id="elementWidth" value="${parseInt(element.style.width)}" step="1">
            </div>
            <div class="form-group">
                <label>高度 (px):</label>
                <input type="number" id="elementHeight" value="${parseInt(element.style.height)}" step="1">
            </div>
            <div class="form-group">
                <label>边框宽度 (px):</label>
                <input type="number" id="elementBorderWidth" value="${parseInt(element.style.borderWidth) || 0}" step="1" min="0">
            </div>
            <div class="form-group">
                <label>边框颜色:</label>
                <div class="color-input-group">
                    <input type="color" id="elementBorderColor" value="${element.style.borderColor || '#000000'}">
                    <span class="color-value" id="elementBorderColorValue">${element.style.borderColor || '#000000'}</span>
                </div>
            </div>
            <div class="form-group">
                <label>圆角 (px):</label>
                <input type="number" id="elementBorderRadius" value="${parseInt(element.style.borderRadius) || 0}" step="1" min="0">
            </div>
            <div class="form-group">
                <label>边框样式:</label>
                <select id="elementBorderStyle">
                    <option value="none" ${element.style.borderStyle === 'none' ? 'selected' : ''}>无边框</option>
                    <option value="solid" ${element.style.borderStyle === 'solid' ? 'selected' : ''}>实线</option>
                    <option value="dashed" ${element.style.borderStyle === 'dashed' ? 'selected' : ''}>虚线</option>
                    <option value="dotted" ${element.style.borderStyle === 'dotted' ? 'selected' : ''}>点线</option>
                    <option value="double" ${element.style.borderStyle === 'double' ? 'selected' : ''}>双线</option>
                </select>
            </div>
            <div class="form-group full-width">
                <label>动画效果:</label>
                <select id="elementAnimationName">
                    <option value="none" ${element.style.animationName === 'none' ? 'selected' : ''}>无动画</option>
                    <option value="bounce" ${element.style.animationName === 'bounce' ? 'selected' : ''}>弹跳</option>
                    <option value="flash" ${element.style.animationName === 'flash' ? 'selected' : ''}>闪烁</option>
                    <option value="pulse" ${element.style.animationName === 'pulse' ? 'selected' : ''}>脉冲</option>
                    <option value="rubberBand" ${element.style.animationName === 'rubberBand' ? 'selected' : ''}>橡皮筋</option>
                    <option value="shake" ${element.style.animationName === 'shake' ? 'selected' : ''}>摇摆</option>
                    <option value="swing" ${element.style.animationName === 'swing' ? 'selected' : ''}>摆动</option>
                    <option value="tada" ${element.style.animationName === 'tada' ? 'selected' : ''}>庆祝</option>
                    <option value="wobble" ${element.style.animationName === 'wobble' ? 'selected' : ''}>摇摆</option>
                    <option value="jello" ${element.style.animationName === 'jello' ? 'selected' : ''}>果冻</option>
                    <option value="bounceIn" ${element.style.animationName === 'bounceIn' ? 'selected' : ''}>弹入</option>
                    <option value="bounceInDown" ${element.style.animationName === 'bounceInDown' ? 'selected' : ''}>从下弹入</option>
                    <option value="bounceInLeft" ${element.style.animationName === 'bounceInLeft' ? 'selected' : ''}>从左弹入</option>
                    <option value="bounceInRight" ${element.style.animationName === 'bounceInRight' ? 'selected' : ''}>从右弹入</option>
                    <option value="bounceInUp" ${element.style.animationName === 'bounceInUp' ? 'selected' : ''}>从上弹入</option>
                    <option value="fadeIn" ${element.style.animationName === 'fadeIn' ? 'selected' : ''}>淡入</option>
                    <option value="fadeInDown" ${element.style.animationName === 'fadeInDown' ? 'selected' : ''}>从下淡入</option>
                    <option value="fadeInLeft" ${element.style.animationName === 'fadeInLeft' ? 'selected' : ''}>从左淡入</option>
                    <option value="fadeInRight" ${element.style.animationName === 'fadeInRight' ? 'selected' : ''}>从右淡入</option>
                    <option value="fadeInUp" ${element.style.animationName === 'fadeInUp' ? 'selected' : ''}>从上淡入</option>
                    <option value="slideInDown" ${element.style.animationName === 'slideInDown' ? 'selected' : ''}>从下滑入</option>
                    <option value="slideInLeft" ${element.style.animationName === 'slideInLeft' ? 'selected' : ''}>从左滑入</option>
                    <option value="slideInRight" ${element.style.animationName === 'slideInRight' ? 'selected' : ''}>从右滑入</option>
                    <option value="slideInUp" ${element.style.animationName === 'slideInUp' ? 'selected' : ''}>从上滑入</option>
                    <option value="zoomIn" ${element.style.animationName === 'zoomIn' ? 'selected' : ''}>放大进入</option>
                    <option value="zoomInDown" ${element.style.animationName === 'zoomInDown' ? 'selected' : ''}>从下放大进入</option>
                    <option value="zoomInLeft" ${element.style.animationName === 'zoomInLeft' ? 'selected' : ''}>从左放大进入</option>
                    <option value="zoomInRight" ${element.style.animationName === 'zoomInRight' ? 'selected' : ''}>从右放大进入</option>
                    <option value="zoomInUp" ${element.style.animationName === 'zoomInUp' ? 'selected' : ''}>从上放大进入</option>
                </select>
            </div>
            <div class="form-group">
                <label>动画时长 (s):</label>
                <input type="number" id="elementAnimationDuration" value="${parseFloat(element.style.animationDuration) || 1}" step="0.1" min="0.1" max="10">
            </div>
            <div class="form-group">
                <label>动画延迟 (s):</label>
                <input type="number" id="elementAnimationDelay" value="${parseFloat(element.style.animationDelay) || 0}" step="0.1" min="0" max="10">
            </div>
            <div class="form-group">
                <label>动画次数:</label>
                <select id="elementAnimationIterationCount">
                    <option value="1" ${element.style.animationIterationCount === '1' ? 'selected' : ''}>1次</option>
                    <option value="2" ${element.style.animationIterationCount === '2' ? 'selected' : ''}>2次</option>
                    <option value="3" ${element.style.animationIterationCount === '3' ? 'selected' : ''}>3次</option>
                    <option value="infinite" ${element.style.animationIterationCount === 'infinite' ? 'selected' : ''}>无限循环</option>
                </select>
            </div>
            <div class="form-group">
                <label>动画填充模式:</label>
                <select id="elementAnimationFillMode">
                    <option value="both" ${element.style.animationFillMode === 'both' ? 'selected' : ''}>前后保持</option>
                    <option value="forwards" ${element.style.animationFillMode === 'forwards' ? 'selected' : ''}>保持结束状态</option>
                    <option value="backwards" ${element.style.animationFillMode === 'backwards' ? 'selected' : ''}>保持开始状态</option>
                    <option value="none" ${element.style.animationFillMode === 'none' ? 'selected' : ''}>不保持</option>
                </select>
            </div>
            <div class="form-group full-width">
                <label>层级 (z-index):</label>
                <input type="number" id="elementZIndex" value="${parseInt(element.style.zIndex) || 0}" step="1" min="0">
                <div class="z-index-controls">
                    <button type="button" id="bringToFront" class="btn btn-sm">置顶</button>
                    <button type="button" id="sendToBack" class="btn btn-sm">置底</button>
                </div>
            </div>
        `;

        return html;
    }

    /**
     * 应用事件处理器到元素
     * @param {HTMLElement} elementDiv - DOM元素
     * @param {Object} element - 元素对象
     */
    applyEventHandlers(elementDiv, element) {
        if (!element.events) return;

        // 点击事件
        if (element.events.click && element.events.click !== 'none') {
            elementDiv.addEventListener('click', (e) => {
                e.stopPropagation();
                this.handleEvent(element.events.click, element.events.clickLink, element.events.clickCustom);
            });
        }

        // 触摸事件
        if (element.events.touch && element.events.touch !== 'none') {
            elementDiv.addEventListener('touchstart', (e) => {
                e.stopPropagation();
                this.handleEvent(element.events.touch, element.events.touchLink, element.events.touchCustom);
            });
        }

        // 悬停事件
        if (element.events.hover && element.events.hover !== 'none') {
            elementDiv.addEventListener('mouseenter', (e) => {
                e.stopPropagation();
                this.handleEvent(element.events.hover, null, element.events.hoverCustom);
            });
        }
    }

    /**
     * 处理事件
     * @param {string} eventType - 事件类型
     * @param {string} link - 链接地址
     * @param {string} customCode - 自定义代码
     */
    handleEvent(eventType, link, customCode) {
        switch (eventType) {
            case 'alert':
                alert('元素被点击了！');
                break;
            case 'link':
                if (link) {
                    window.open(link, '_blank');
                }
                break;
            case 'custom':
                if (customCode) {
                    try {
                        eval(customCode);
                    } catch (error) {
                        console.error('自定义代码执行错误:', error);
                    }
                }
                break;
        }
    }

    /**
     * 设置事件监听器
     * @param {Object} element - 元素对象
     */
    setupEventListeners(element) {
        // 初始化events对象
        if (!element.events) {
            element.events = {
                click: 'none',
                touch: 'none',
                hover: 'none'
            };
        }

        // 点击事件
        const clickEventSelect = document.getElementById('elementClickEvent');
        if (clickEventSelect) {
            clickEventSelect.addEventListener('change', (e) => {
                element.events.click = e.target.value;
                this.toggleEventGroup('click', e.target.value);
            });
        }

        // 点击链接
        const clickLinkInput = document.getElementById('elementClickLink');
        if (clickLinkInput) {
            clickLinkInput.addEventListener('input', (e) => {
                element.events.clickLink = e.target.value;
            });
        }

        // 点击自定义代码
        const clickCustomTextarea = document.getElementById('elementClickCustom');
        if (clickCustomTextarea) {
            clickCustomTextarea.addEventListener('input', (e) => {
                element.events.clickCustom = e.target.value;
            });
        }

        // 触摸事件
        const touchEventSelect = document.getElementById('elementTouchEvent');
        if (touchEventSelect) {
            touchEventSelect.addEventListener('change', (e) => {
                element.events.touch = e.target.value;
                this.toggleEventGroup('touch', e.target.value);
            });
        }

        // 触摸链接
        const touchLinkInput = document.getElementById('elementTouchLink');
        if (touchLinkInput) {
            touchLinkInput.addEventListener('input', (e) => {
                element.events.touchLink = e.target.value;
            });
        }

        // 触摸自定义代码
        const touchCustomTextarea = document.getElementById('elementTouchCustom');
        if (touchCustomTextarea) {
            touchCustomTextarea.addEventListener('input', (e) => {
                element.events.touchCustom = e.target.value;
            });
        }

        // 悬停事件
        const hoverEventSelect = document.getElementById('elementHoverEvent');
        if (hoverEventSelect) {
            hoverEventSelect.addEventListener('change', (e) => {
                element.events.hover = e.target.value;
                this.toggleEventGroup('hover', e.target.value);
            });
        }

        // 悬停自定义代码
        const hoverCustomTextarea = document.getElementById('elementHoverCustom');
        if (hoverCustomTextarea) {
            hoverCustomTextarea.addEventListener('input', (e) => {
                element.events.hoverCustom = e.target.value;
            });
        }
    }

    /**
     * 切换事件组显示/隐藏
     * @param {string} eventType - 事件类型
     * @param {string} eventValue - 事件值
     */
    toggleEventGroup(eventType, eventValue) {
        const linkGroup = document.getElementById(eventType + 'LinkGroup');
        const customGroup = document.getElementById(eventType + 'CustomGroup');
        
        if (linkGroup) {
            linkGroup.style.display = eventValue === 'link' ? 'block' : 'none';
        }
        if (customGroup) {
            customGroup.style.display = eventValue === 'custom' ? 'block' : 'none';
        }
    }

    /**
     * 设置属性面板事件监听
     * @param {Object} element - 元素对象
     */
    setupPropertyListeners(element) {
        // Tab切换功能
        const tabBtns = document.querySelectorAll('.tab-btn');
        tabBtns.forEach(btn => {
            btn.addEventListener('click', (e) => {
                const tabName = e.target.getAttribute('data-tab');
                
                // 移除所有active类
                tabBtns.forEach(b => b.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
                
                // 添加active类到当前tab
                e.target.classList.add('active');
                document.getElementById(tabName + '-tab').classList.add('active');
            });
        });

        // 事件监听器
        this.setupEventListeners(element);

        // 内容更新 - 使用事件委托，因为属性面板是动态生成的
        const propertiesPanel = document.getElementById('propertiesContent');
        console.log('设置属性面板监听器 - 查找propertiesContent:', propertiesPanel);
        if (propertiesPanel) {
            // 移除之前的事件监听器
            propertiesPanel.removeEventListener('input', this.handleContentInput);
            // 添加新的事件监听器
            this.handleContentInput = (e) => {
                if (e.target && e.target.id === 'elementContent') {
                    console.log('属性面板内容变化:', e.target.value);
                    console.log('当前元素:', element);
                    element.content = e.target.value;
                    console.log('元素content已更新为:', element.content);
                    this.updateElementDisplay(element);
                }
            };
            propertiesPanel.addEventListener('input', this.handleContentInput);
            console.log('已设置属性面板内容监听器');
        } else {
            console.error('找不到propertiesContent容器');
        }

        // 样式更新
        const styleInputs = ['fontSize', 'textColor', 'textAlign', 'backgroundColor', 'imageUrl', 'buttonText', 'buttonBgColor', 'buttonTextColor', 'elementWidth', 'elementHeight', 'elementBorderWidth', 'elementBorderColor', 'elementBorderRadius', 'elementBorderStyle', 'elementAnimationName', 'elementAnimationDuration', 'elementAnimationDelay', 'elementAnimationIterationCount', 'elementAnimationFillMode', 'elementZIndex'];
        styleInputs.forEach(inputId => {
            const input = document.getElementById(inputId);
            if (input) {
                input.addEventListener('input', (e) => {
                    this.updateElementStyle(element, inputId, e.target.value);
                });
                // 为select元素添加change事件
                if (input.tagName === 'SELECT') {
                    input.addEventListener('change', (e) => {
                        this.updateElementStyle(element, inputId, e.target.value);
                    });
                }
            }
        });

        // 颜色选择器特殊处理
        const colorInputs = ['textColor', 'backgroundColor', 'buttonBgColor', 'buttonTextColor', 'elementBorderColor'];
        colorInputs.forEach(inputId => {
            const colorInput = document.getElementById(inputId);
            const colorValueSpan = document.getElementById(inputId + 'Value');
            if (colorInput && colorValueSpan) {
                colorInput.addEventListener('input', (e) => {
                    colorValueSpan.textContent = e.target.value;
                });
                colorInput.addEventListener('change', (e) => {
                    colorValueSpan.textContent = e.target.value;
                });
            }
        });

        // z-index控制按钮
        const bringToFrontBtn = document.getElementById('bringToFront');
        if (bringToFrontBtn) {
            bringToFrontBtn.addEventListener('click', () => {
                this.bringToFront(element);
            });
        }

        const sendToBackBtn = document.getElementById('sendToBack');
        if (sendToBackBtn) {
            sendToBackBtn.addEventListener('click', () => {
                this.sendToBack(element);
            });
        }

        // 删除元素按钮
        const deleteBtn = document.getElementById('deleteElement');
        if (deleteBtn) {
            deleteBtn.addEventListener('click', () => {
                this.deleteElement(element);
            });
        }
    }

    /**
     * 更新元素显示
     * @param {Object} element - 元素对象
     */
    updateElementDisplay(element) {
        console.log('updateElementDisplay被调用 - 元素ID:', element.id, '类型:', element.type, '内容:', element.content);
        const elementDiv = document.getElementById(element.id);
        console.log('找到的DOM元素:', elementDiv);
        if (!elementDiv) {
            console.error('找不到DOM元素:', element.id);
            return;
        }

        switch (element.type) {
            case 'text':
                console.log('更新文本元素 - 原内容:', elementDiv.textContent, '新内容:', element.content);
                elementDiv.textContent = element.content;
                console.log('文本元素更新后:', elementDiv.textContent);
                break;
            case 'button':
                console.log('更新按钮元素 - 原内容:', elementDiv.textContent, '新内容:', element.content);
                elementDiv.textContent = element.content;
                console.log('按钮元素更新后:', elementDiv.textContent);
                break;
            case 'input':
                const input = elementDiv.querySelector('input');
                console.log('找到的input子元素:', input);
                if (input) {
                    console.log('更新输入框 - 原value:', input.value, '原placeholder:', input.placeholder, '新内容:', element.content);
                    input.value = element.content;
                    console.log('输入框更新后 - value:', input.value, 'placeholder:', input.placeholder);
                } else {
                    console.error('找不到input子元素');
                }
                break;
            case 'image':
                const img = elementDiv.querySelector('img');
                console.log('找到的img子元素:', img);
                if (img) {
                    console.log('更新图片 - 原src:', img.src, '新内容:', element.content);
                    img.src = element.content;
                    console.log('图片更新后 - src:', img.src);
                } else {
                    console.error('找不到img子元素');
                }
                break;
        }
    }

    /**
     * 更新元素样式
     * @param {Object} element - 元素对象
     * @param {string} inputId - 输入框ID
     * @param {string} value - 新值
     */
    updateElementStyle(element, inputId, value) {
        const elementDiv = document.getElementById(element.id);
        if (!elementDiv) return;

        switch (inputId) {
            case 'fontSize':
                element.style.fontSize = value + 'px';
                elementDiv.style.fontSize = element.style.fontSize;
                break;
            case 'textColor':
                element.style.color = value;
                elementDiv.style.color = element.style.color;
                break;
            case 'textAlign':
                element.style.textAlign = value;
                elementDiv.style.textAlign = element.style.textAlign;
                break;
            case 'backgroundColor':
                element.style.backgroundColor = value;
                elementDiv.style.backgroundColor = element.style.backgroundColor;
                break;
            case 'imageUrl':
                element.content = value;
                const img = elementDiv.querySelector('img');
                if (img) {
                    img.src = value;
                }
                break;
            case 'buttonText':
                element.content = value;
                elementDiv.textContent = value;
                break;
            case 'buttonBgColor':
                element.style.backgroundColor = value;
                elementDiv.style.backgroundColor = element.style.backgroundColor;
                break;
            case 'buttonTextColor':
                element.style.color = value;
                elementDiv.style.color = element.style.color;
                break;
            case 'elementWidth':
                element.style.width = value + 'px';
                elementDiv.style.width = element.style.width;
                break;
            case 'elementHeight':
                element.style.height = value + 'px';
                elementDiv.style.height = element.style.height;
                break;
            case 'elementBorderWidth':
                element.style.borderWidth = value + 'px';
                elementDiv.style.borderWidth = element.style.borderWidth;
                break;
            case 'elementBorderColor':
                element.style.borderColor = value;
                elementDiv.style.borderColor = element.style.borderColor;
                break;
            case 'elementBorderRadius':
                element.style.borderRadius = value + 'px';
                elementDiv.style.borderRadius = element.style.borderRadius;
                // 如果是图片元素，也要更新内层img的border-radius
                if (element.type === 'image') {
                    const img = elementDiv.querySelector('img');
                    if (img) {
                        img.style.borderRadius = element.style.borderRadius;
                    }
                }
                break;
            case 'elementBorderStyle':
                element.style.borderStyle = value;
                elementDiv.style.borderStyle = element.style.borderStyle;
                break;
            case 'elementAnimationName':
                element.style.animationName = value;
                if (value === 'none') {
                    elementDiv.style.animation = 'none';
                    // 移除所有animate.css类
                    elementDiv.classList.remove('animate__animated');
                    elementDiv.classList.forEach(cls => {
                        if (cls.startsWith('animate__')) {
                            elementDiv.classList.remove(cls);
                        }
                    });
                } else {
                    // 移除之前的动画类
                    elementDiv.classList.forEach(cls => {
                        if (cls.startsWith('animate__')) {
                            elementDiv.classList.remove(cls);
                        }
                    });
                    // 添加新的动画类
                    elementDiv.classList.add('animate__animated', `animate__${value}`);
                    // 使用CSS自定义属性设置动画参数
                    elementDiv.style.setProperty('--animate-duration', element.style.animationDuration);
                    elementDiv.style.setProperty('--animate-delay', element.style.animationDelay);
                    elementDiv.style.animationFillMode = element.style.animationFillMode;
                    
                    // 处理动画次数
                    if (element.style.animationIterationCount === 'infinite') {
                        elementDiv.classList.add('animate__infinite');
                    } else {
                        elementDiv.classList.add(`animate__repeat-${element.style.animationIterationCount}`);
                    }
                    
                    // 强制触发动画
                    elementDiv.style.animation = 'none';
                    elementDiv.offsetHeight; // 触发重排
                    elementDiv.style.animation = '';
                }
                break;
            case 'elementAnimationDuration':
                element.style.animationDuration = value + 's';
                if (element.style.animationName !== 'none') {
                    elementDiv.style.setProperty('--animate-duration', element.style.animationDuration);
                }
                break;
            case 'elementAnimationDelay':
                element.style.animationDelay = value + 's';
                if (element.style.animationName !== 'none') {
                    elementDiv.style.setProperty('--animate-delay', element.style.animationDelay);
                }
                break;
            case 'elementAnimationIterationCount':
                element.style.animationIterationCount = value;
                if (element.style.animationName !== 'none') {
                    // 移除之前的重复类
                    elementDiv.classList.remove('animate__repeat-1', 'animate__repeat-2', 'animate__repeat-3', 'animate__infinite');
                    // 添加新的重复类
                    if (value === 'infinite') {
                        elementDiv.classList.add('animate__infinite');
                    } else {
                        elementDiv.classList.add(`animate__repeat-${value}`);
                    }
                }
                break;
            case 'elementAnimationFillMode':
                element.style.animationFillMode = value;
                if (element.style.animationName !== 'none') {
                    elementDiv.style.animationFillMode = element.style.animationFillMode;
                }
                break;
            case 'elementZIndex':
                element.style.zIndex = parseInt(value);
                elementDiv.style.zIndex = element.style.zIndex;
                break;
        }
    }

    /**
     * 删除元素
     * @param {Object} element - 元素对象
     */
    deleteElement(element) {
        // 从DOM中移除元素
        const elementDiv = document.getElementById(element.id);
        if (elementDiv) {
            elementDiv.remove();
        }

        // 从元素数组中移除
        const index = this.elements.findIndex(el => el.id === element.id);
        if (index > -1) {
            this.elements.splice(index, 1);
        }

        // 更新画布提示文案显示状态
        this.updateCanvasPlaceholder();

        // 隐藏属性面板
        this.hideElementProperties();
    }

    /**
     * 设置网格拖拽区域
     * @param {HTMLElement} gridElement - 网格DOM元素
     * @param {Object} gridData - 网格数据
     */
    setupGridDropZone(gridElement, gridData) {
        const gridContent = gridElement.querySelector('.grid-content');
        
        gridContent.addEventListener('dragover', (e) => {
            e.preventDefault();
            gridContent.classList.add('grid-drag-over');
        });

        gridContent.addEventListener('dragleave', (e) => {
            if (!gridContent.contains(e.relatedTarget)) {
                gridContent.classList.remove('grid-drag-over');
            }
        });

        gridContent.addEventListener('drop', (e) => {
            e.preventDefault();
            gridContent.classList.remove('grid-drag-over');
            
            const elementType = e.dataTransfer.getData('text/plain');
            if (elementType) {
                this.addElementToGrid(elementType, gridData.id);
            }
        });
    }

    /**
     * 添加元素到网格
     * @param {string} elementType - 元素类型
     * @param {string} gridId - 网格ID
     */
    addElementToGrid(elementType, gridId) {
        const element = this.createElement(elementType, 0, 0);
        element.parentGrid = gridId;
        element.style.width = '100%';
        element.style.height = 'auto';
        element.style.position = 'static';

        this.renderGridElement(element, gridId);
    }

    /**
     * 渲染网格中的元素
     * @param {Object} element - 元素对象
     * @param {string} gridId - 网格ID
     */
    renderGridElement(element, gridId) {
        const gridContent = document.querySelector(`[data-grid-id="${gridId}"]`);
        if (!gridContent) return;

        const gridItem = document.createElement('div');
        gridItem.className = 'grid-item';
        gridItem.style.cssText = `
            background: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 8px;
            min-height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
        `;

        switch (element.type) {
            case 'text':
                gridItem.textContent = element.content;
                break;
            case 'image':
                const img = document.createElement('img');
                img.src = element.content;
                img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: cover;';
                gridItem.appendChild(img);
                break;
            case 'button':
                gridItem.textContent = element.content;
                gridItem.style.cssText += 'background: #007bff; color: white; cursor: pointer;';
                break;
        }

        gridContent.appendChild(gridItem);
    }

    /**
     * 获取所有元素
     * @returns {Array} 元素数组
     */
    getElements() {
        return this.elements;
    }

    /**
     * 将元素置顶
     * @param {Object} element - 元素对象
     */
    bringToFront(element) {
        const maxZIndex = this.getMaxZIndex();
        element.style.zIndex = maxZIndex + 1;
        
        const elementDiv = document.getElementById(element.id);
        if (elementDiv) {
            elementDiv.style.zIndex = element.style.zIndex;
        }
        
        // 更新属性面板中的z-index值
        const zIndexInput = document.getElementById('elementZIndex');
        if (zIndexInput) {
            zIndexInput.value = element.style.zIndex;
        }
    }

    /**
     * 将元素置底
     * @param {Object} element - 元素对象
     */
    sendToBack(element) {
        element.style.zIndex = 0;
        
        const elementDiv = document.getElementById(element.id);
        if (elementDiv) {
            elementDiv.style.zIndex = element.style.zIndex;
        }
        
        // 更新属性面板中的z-index值
        const zIndexInput = document.getElementById('elementZIndex');
        if (zIndexInput) {
            zIndexInput.value = element.style.zIndex;
        }
    }

    /**
     * 清空所有元素
     */
    clearElements() {
        this.elements = [];
        this.canvas.innerHTML = '';
        this.hideElementProperties();
        
        // 更新画布提示文案显示状态
        this.updateCanvasPlaceholder();
    }

    /**
     * 更新画布提示文案的显示状态
     */
    updateCanvasPlaceholder() {
        const placeholder = this.canvas.querySelector('.canvas-placeholder');
        if (this.elements.length === 0) {
            // 没有元素时显示提示
            if (!placeholder) {
                const placeholderDiv = document.createElement('div');
                placeholderDiv.className = 'canvas-placeholder';
                placeholderDiv.innerHTML = '<p>拖拽左侧元素到此处开始设计</p>';
                this.canvas.appendChild(placeholderDiv);
            } else {
                placeholder.style.display = 'block';
            }
        } else {
            // 有元素时隐藏提示
            if (placeholder) {
                placeholder.style.display = 'none';
            }
        }
    }
    
    /**
     * 禁用Swiper滑动（现在Swiper已默认禁用触摸，此方法保留以防将来需要）
     */
    disableSwiper() {
        // Swiper已在初始化时禁用触摸滑动，此方法暂时为空
        // 保留此方法是为了向后兼容
    }
    
    /**
     * 启用Swiper滑动（现在Swiper已默认禁用触摸，此方法保留以防将来需要）
     */
    enableSwiper() {
        // Swiper已在初始化时禁用触摸滑动，此方法暂时为空
        // 保留此方法是为了向后兼容
    }
}

// 导出类（如果使用模块系统）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ElementManager;
}
